package com.freshcity.component.container
{
	import fl.controls.LabelButton;
	import fl.core.InvalidationType;
	import fl.core.UIComponent;
	import fl.events.ListEvent;
	import fl.managers.IFocusManagerComponent;
	
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.ui.Keyboard;
	
	/** 列出事件 */
	[Event(name="change",type="flash.events.Event")]
	[Event(name="itemClick",type="fl.events.ListEvent")]
	[Event(name="itemRollOut",type="fl.events.ListEvent")]
	[Event(name="itemRollOver",type="fl.events.ListEvent")]
	
	/** 列出样式 */
	[Style(name="upSkin", type="Class")]
	[Style(name="overSkin", type="Class")]
	[Style(name="downSkin", type="Class")]
	[Style(name="selectedUpSkin", type="Class")]
	[Style(name="selectedOverSkin", type="Class")]
	[Style(name="selectedDownSkin", type="Class")]
	[Style(name="textPadding", type="Number", format="Length")]
	/**
	 * 选项卡
	 * @author pw
	 * 
	 */	
	public class TabBar extends UIComponent implements IFocusManagerComponent
	{
		/** 存储我们创建的按钮 */
		public var arrBtns:Array;
		/** 存储各个按钮的文字 */
		protected var _arrBtnLabels:Array;
		/** 被选择的索引 */
		protected var _selectedIndex:int = 0;
		/** 按钮之间间隔 */
		protected var _btnSpace:Number = 0;
		/** 布局方向 */
		protected var _direction:String = LayoutDirection.HORIZONTAL;
		/** 默认的类样式 因为是static的,所以不会与父类的样式冲突 */
		private static var defaultStyles:Object = {
			skin:"TabBar_skin",
			upSkin:"TabBar_upSkin",
			overSkin:"TabBar_overSkin",
			downSkin:"TabBar_downSkin",
			selectedSkin:"TabBar_selectedSkin",
			bgskin:"TabBar_bgskin",
			textPadding:2
		}
		/** 标题按钮样式的映射 */
		protected static const BUTTON_STYLES:Object = {
			upSkin:"upSkin",
			downSkin:"downSkin",
			overSkin:"overSkin",
			selectedUpSkin:"selectedSkin",
			selectedOverSkin:"selectedSkin",
			selectedDownSkin:"selectedSkin",
			textPadding:"textPadding"
		}
		private var background:DisplayObject;
		private var _btnHeight:Number;
		private var _btnWidth:Number;
		public function TabBar()
		{
			super();
			arrBtns = [];
			_arrBtnLabels = ["Tab1", "Tab2"];
		}
		/** 利用mergeStyles()把两个类的样式合并 */
		public static function getStyleDefinition():Object {
			return mergeStyles(defaultStyles, UIComponent.getStyleDefinition());
		}
		/** 重写初始化显示对象 */
		override protected function configUI():void{
			super.configUI();
		}
		/** 重写重绘方法（核心） */
		override protected function draw():void{
			if (isInvalid(InvalidationType.STYLES, InvalidationType.DATA)){
				drawBtns();
			}
			if (isInvalid(InvalidationType.STYLES)){
				updateBtnStyles();
			}
			if (isInvalid(InvalidationType.SIZE, InvalidationType.DATA)){
				doLayout();
			}
			super.draw();
		}
		/**
		 * 绘制选项卡的按钮
		 */		
		protected function drawBtns():void {
			var len:uint = arrBtns.length;
			for(var i:uint = 0; i < len; i++){
				var btn:LabelButton = arrBtns[i];
				//必须取消注册的监听器
				btn.removeEventListener(MouseEvent.CLICK, clickHandler);
				btn.removeEventListener(MouseEvent.MOUSE_OVER, mouseEventHandler);
				btn.removeEventListener(MouseEvent.MOUSE_OUT, mouseEventHandler);
				btn.removeEventListener(Event.CHANGE, changeHandler);
				this.removeChild(btn);
			}
			arrBtns = [];
			
			len = _arrBtnLabels.length;
			for(var j:uint = 0; j < len; j++){
				//建立新的按钮
				var label:String = _arrBtnLabels[j];
				var btnNew:LabelButton = new LabelButton();
				btnNew.label = label;
				btnNew.toggle = true;
				btnNew.tabEnabled = false;
				
				copyStylesToChild(btnNew, BUTTON_STYLES);
				btnNew.addEventListener(MouseEvent.CLICK, clickHandler);
				btnNew.addEventListener(Event.CHANGE, changeHandler);
				btnNew.addEventListener(MouseEvent.MOUSE_OVER, mouseEventHandler);
				btnNew.addEventListener(MouseEvent.MOUSE_OUT, mouseEventHandler);
				this.addChild(btnNew);
				arrBtns.push(btnNew);
			}
			
			//设置被选择的标题按钮的selected属性
			var btnSelected:LabelButton = arrBtns[_selectedIndex];
			if(btnSelected)
				btnSelected.selected = true;
		}
		
		protected function drawBackground():void {
			
			var bg:DisplayObject = background;
			
			background = getDisplayObjectInstance(getStyleValue("bgskin"));
			addChildAt(background, 0);
			
			if (bg != null && bg != background) {
				removeChild(bg);
			}
		}		
		/**
		 * 布局设计
		 */		
		protected function doLayout():void {
			var len:uint = arrBtns.length;
			var btn:LabelButton;
			
			drawBackground();
			
			if(_direction == LayoutDirection.HORIZONTAL){
				for(var i:uint = 0; i < len; i++){
					btn = arrBtns[i];
					btn.x = (_btnWidth + _btnSpace) * i;
					btn.setSize(_btnWidth, height);
					//强制按钮重绘
					btn.drawNow();
				}
				background.width = width;
				background.height = 0.5;
				background.y = height-1;
			}else{
				for(var j:uint = 0; j < len; j++){
					btn = arrBtns[j];
					btn.y = (_btnHeight + _btnSpace) * j;
					btn.setSize(width, _btnHeight);
					//强制按钮重绘
					btn.drawNow();
				}
				background.height = height;
				background.width = 0.5;
				background.x = width-1;
			}
		}
		/**
		 * 统一改变按钮的样式
		 */		
		protected function updateBtnStyles():void {
			var len:uint = arrBtns.length;
			for(var i:uint = 0; i < len; i++){
				copyStylesToChild(arrBtns[i], BUTTON_STYLES);
			}
		}
		protected function clickHandler(evt:MouseEvent):void{
			var btn:LabelButton = evt.target as LabelButton;
			evt.stopImmediatePropagation();
			if(!btn.selected){
				btn.selected = true;
			}else{
				var index:uint = arrBtns.indexOf(btn);
				selectedIndex = index;
			}
		}
		protected function mouseEventHandler(evt:MouseEvent):void{
			var type:String = "";
			switch(evt.type){
				case MouseEvent.MOUSE_OUT:
					type = ListEvent.ITEM_ROLL_OUT;
					break;
				case MouseEvent.MOUSE_OVER:
					type = ListEvent.ITEM_ROLL_OVER;
					break;
			}
			evt.stopImmediatePropagation();
			var btn:LabelButton = evt.target as LabelButton;
			var index:uint = arrBtns.indexOf(btn);
			dispatchEvent(new ListEvent(type, false, true, 0, 0, index, btn.label));
		}
		private function changeHandler(evt:Event):void{
			//阻止按钮发出change事件
			evt.stopImmediatePropagation();
		}
		override protected function keyDownHandler(evt:KeyboardEvent):void {
			switch (evt.keyCode) {
				case Keyboard.DOWN:
				case Keyboard.RIGHT:
					if(_selectedIndex == _arrBtnLabels.length - 1){
						selectedIndex = 0;
					}else{
						selectedIndex++;
					}
					break;
				case Keyboard.UP:
				case Keyboard.LEFT:
					if(_selectedIndex == 0){
						selectedIndex = _arrBtnLabels.length - 1;
					}else{
						selectedIndex--;
					}
					break;
				case Keyboard.END:
					selectedIndex = _arrBtnLabels.length - 1;
					break;
				case Keyboard.HOME:
					selectedIndex = 0;
					break;
			}
		}
		/** 子项的个数 */
		public function get length():int{
			return _arrBtnLabels.length;
		}
		/** 被选的索引 */
		[Inspectable(defaultValue = 0)]
		public function get selectedIndex():int{
			return _selectedIndex;
		}
		public function set selectedIndex(index:int):void{
			if(_selectedIndex != index && arrBtns.length > 0){
				arrBtns[_selectedIndex].selected = false;
				_selectedIndex = index;
				arrBtns[_selectedIndex].selected = true;
				dispatchEvent(new ListEvent(ListEvent.ITEM_CLICK, false, true, 0, 0, index, arrBtns[_selectedIndex].label));
				invalidate(InvalidationType.SELECTED);
			}else{
				_selectedIndex = index;
			}
		}
		/** 按钮之间间隔 */
		[Inspectable(name="ButtonSpace", defaultValue = 0)]
		public function get btnSpace():Number{
			return _btnSpace;
		}
		public function set btnSpace(v:Number):void{
			_btnSpace = v;
			invalidate(InvalidationType.SIZE);
		}
		/** 按钮高度 */
		[Inspectable(name="ButtonHeight", defaultValue = 30)]
		public function get btnHeight():Number{
			return _btnHeight;
		}
		public function set btnHeight(v:Number):void{
			_btnHeight = v;
			invalidate(InvalidationType.SIZE);
		}
		/** 按钮宽度 */
		[Inspectable(name="ButtonWidth", defaultValue = 60)]
		public function get btnWidth():Number{
			return _btnWidth;
		}
		public function set btnWidth(v:Number):void{
			_btnWidth = v;
			invalidate(InvalidationType.SIZE);
		}
		
		
		[Inspectable(name="Labels", defaultValue="Tab1,Tab2")]
		public function get arrBtnLabels():Array{
			return _arrBtnLabels;
		}
		public function set arrBtnLabels(arr:Array):void{
			_arrBtnLabels = arr;
			invalidate(InvalidationType.DATA);
		}
		[Inspectable(enumeration="horizontal,vertical", defaultValue="horizontal")]
		public function get direction():String { 
			return _direction;
		}
		public function set direction(value:String):void {
			if(_direction == value)return;
			_direction = value;
			invalidate(InvalidationType.SIZE);
		}
	}
}